package com.xmim.server.examples;

import com.xmim.core.entity.Message;
import com.xmim.core.session.user.UserSession;
import com.xmim.fulcrum.FulcrumDiscover;
import com.xmim.fulcrum.FulcrumFactory;
import com.xmim.server.session.DefaultLocalSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

@ChannelHandler.Sharable
public class NettyChannelHandler extends SimpleChannelInboundHandler<Message> {
    private final FulcrumDiscover discover;
    private final FulcrumFactory factory;

    public NettyChannelHandler(FulcrumDiscover discover) {
        this.discover = discover;
        this.factory = discover.getFactory();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
        UserSession session = DefaultLocalSession.getSession(ctx.channel());
        discover.discover(session, message);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        DefaultLocalSession session = new DefaultLocalSession(factory, UUID.randomUUID().toString());
        session.bind(ctx.channel());
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        UserSession session = DefaultLocalSession.getSession(ctx.channel());
        if (session != null) {
            session.unbind();
        }
    }
}
